from django.http import HttpResponse
import json
#时间包
import time
#导入os
import os
#导入yolo
from ultralytics import YOLO

def detect_img(request):
    #获取文件数据
   file = request.FILES.get("file")
   #为了保证保存的文件名不同，添加时间戳
   file_name = str(int(time.time()))
   print(file_name)
   #后去文件后缀
   suffix = str(file).split(".")[-1]
   print(suffix)
   #保存文件
   with open(f"./static/detectImage/{file_name}.{suffix}", "wb") as f:
         for line in file:
            f.write(line)
   #获取当前项目的根路径
   root_path= os.path.dirname(os.getcwd())
   print(f'root_path={root_path}')
   #设置模型路径
   model_path = os.path.join(root_path,"Web/weights","best.pt")
   #加载模型
   model = YOLO(model_path)
   #模型检测
   results = model([f"./static/detectImage/{file_name}.{suffix}"])
   #获取检测结果
   for result in results:
      result.save(filename=f"./static/resultImage/{file_name}.{suffix}")
   data ={"code":200,"resultUrl":f"/static/resultImage/{file_name}.{suffix}"}
   return HttpResponse(json.dumps(data),content_type="application/json")